package models

import (
	"encoding/json"
	"log"
	"mzxk/nono"

	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

//User user-user操作的主要结构
type User struct {
	User             string //用户名
	NickName         string
	RealName         string
	ID               string
	UserVerify       string
	UserVerifyLv     int64
	Referrer         string
	Pwd              string `json:"-"` //密码
	RegIP            string `json:"-"` //注册IP
	Time             string `json:"-"` //注册时间
	Email            string //信箱
	Phone            string //手机号码
	IsLocked         bool   `json:"-"` //锁定账号
	IsBalanceLocked  bool   `json:"-"` //锁定余额
	IsWithdrawLocked int64  `json:"-"` //余额锁定时间
	Viplv            int64
	Group            string //群组
	Address          map[string]string
	WrAddress        []WrAddress
	Favourite        string
	GoogleKey        string `json:"-"`
	GoogleVerify     bool
	PayPwd           string
	FeeScale         map[string]int64
	Oauth            map[string]string
	coll             *mgo.Collection
	loaded           bool
}

//WrAddress
type WrAddress struct {
	Currency string
	Address  string
	Memo     string
}

//返回表名
func (user *User) GetCollection() string {
	return "user"
}

/*type InParam struct {
	Collection string      `json:"collection"` //表结构
	Selector   interface{} `json:"selector"`   //条件
	Update     interface{} `json:"update"`     //更新
	Operation  interface{} `json:"operation"`  //操作
	DB         string      `json:"db"`         //数据库
}*/

type Result struct {
	OrderAmount  float64 `json:"orderamount"`
	Remainamount float64 `json:"remainamount"`
	Subtract     float64 `json:"subtract"`
	Profit       float64 `json:"profit"`
	User         string  `json:"user"`
	Tradetype    string  `json:"tradetype"`
	Avgprice1    float64 `json:"avgprice1"`
}

func Do(mongo *nono.Mongo) (interface{}, error) {
	//query := mongo.GetMongo(user.GetCollection())

	result := make([]*interface{}, 0)

	coll := mongo.GetMongo("orders")

	err := coll.Pipe([]bson.M{
		{
			"$match": bson.M{"user": "13678026347"},
		},
		{
			"$project": bson.M{"avgprice": 1, "feeamount": 1, "feescale": 1, "fillamount": 1, "ismarket": 1, "lastupdate": 1,
				"orderamount": 1, "orderprice": 1, "pair": 1, "remainamount": 1, "state": 1, "time": 1, "tradetype": 1, "user": 1, "subtract": bson.M{"$subtract": []interface{}{"$orderamount", "$remainamount"}},
			}},
		{
			"$project": bson.M{"avgprice": 1, "feeamount": 1, "feescale": 1, "fillamount": 1, "ismarket": 1, "lastupdate": 1,
				"orderamount": 1, "orderprice": 1, "pair": 1, "remainamount": 1, "state": 1, "time": 1, "tradetype": 1, "user": 1, "subtract": 1, "profit": bson.M{"$multiply": []interface{}{"$subtract", "$avgprice"}},
			}},
		{
			"$group": bson.M{"_id": bson.M{"_id": nil, "user": "$user", "tradetype": "$tradetype"}, "avgpriece": bson.M{"$avg": "$avgprice"},
				"orderamount":  bson.M{"$sum": "$orderamount"},
				"remainamount": bson.M{"$sum": "$remainamount"},
				"subtract":     bson.M{"$sum": "$subtract"},
				"profit":       bson.M{"$sum": "$profit"}},
		},
		{
			"$project": bson.M{"_id": nil, "user": "$_id.user", "tradetype": "$_id.tradetype", "orderamount": 1, "remainamount": 1,
				"avgprice": bson.M{"$divide": []interface{}{"$profit", "$subtract"}}, "subtract": 1, "profit": 1},
		},
		{
			"$project": bson.M{
				"orderamount":   bson.M{"$cond": []interface{}{bson.M{"$eq": []interface{}{"$tradetype", "buy"}}, "$orderamount", 0}},
				"remainamount":  bson.M{"$cond": []interface{}{bson.M{"$eq": []interface{}{"$tradetype", "buy"}}, "$remainamount", 0}},
				"subtract":      bson.M{"$cond": []interface{}{bson.M{"$eq": []interface{}{"$tradetype", "buy"}}, "$subtract", 0}},
				"profit":        bson.M{"$cond": []interface{}{bson.M{"$eq": []interface{}{"$tradetype", "buy"}}, "$profit", 0}},
				"avgprice1":     bson.M{"$cond": []interface{}{bson.M{"$eq": []interface{}{"$tradetype", "buy"}}, "$avgprice", 0}},
				"tradetype":     1,
				"user":          1,
				"sorderamount":  bson.M{"$cond": []interface{}{bson.M{"$eq": []interface{}{"$tradetype", "sell"}}, "$orderamount", 0}},
				"sremainamount": bson.M{"$cond": []interface{}{bson.M{"$eq": []interface{}{"$tradetype", "sell"}}, "$remainamount", 0}},
				"ssubtract":     bson.M{"$cond": []interface{}{bson.M{"$eq": []interface{}{"$tradetype", "sell"}}, "$subtract", 0}},
				"sprofit":       bson.M{"$cond": []interface{}{bson.M{"$eq": []interface{}{"$tradetype", "sell"}}, "$profit", 0}},
				"savgprice1":    bson.M{"$cond": []interface{}{bson.M{"$eq": []interface{}{"$tradetype", "sell"}}, "$avgprice", 0}},
			},
		},
		{
			"$project": bson.M{
				"orderamount": 1, "remainamount": 1, "subtract": 1, "profit": 1, "avgprice": 1, "user": 1,
				"sorderamount": 1, "sremainamount": 1, "ssubtract": 1, "sprofit": 1, "savgprice1": 1,
				"surplus":      bson.M{"$subtract": []interface{}{"$subtract", "$ssubtract"}},
				"surplusPrice": bson.M{"$subtract": []interface{}{"$savgprice1", "$avgprice1"}},
			},
		},
		{
			"$group": bson.M{"_id": "$user",
				"orderamount":   bson.M{"$sum": "$orderamount"},
				"remainamount":  bson.M{"$sum": "$remainamount"},
				"subtract":      bson.M{"$sum": "$subtract"},
				"profit":        bson.M{"$sum": "$profit"},
				"avgprice1":     bson.M{"$sum": "$avgprice1"},
				"sorderamount":  bson.M{"$sum": "$sorderamount"},
				"sremainamount": bson.M{"$sum": "$sremainamount"},
				"ssubtract":     bson.M{"$sum": "$ssubtract"},
				"sprofit":       bson.M{"$sum": "$sprofit"},
				"savgprice1":    bson.M{"$sum": "$savgprice1"},
				"surplus":       bson.M{"$sum": "$surplus"},
				"surplusPrice":  bson.M{"$sum": "$surplusPrice"}},
		},
		{
			"$project": bson.M{"orderamount": 1, "remainamount": 1, "subtract": 1, "profit": 1, "avgprice": 1, "user": 1,
				"sorderamount": 1, "sremainamount": 1, "ssubtract": 1, "sprofit": 1, "savgprice1": 1, "surplus": 1, "surplusPrice": 1,
				"totalProfit": bson.M{"$multiply": []interface{}{"$surplusPrice", "$subtract"}}},
		},
	}).All(&result)

	str, _ := json.Marshal(result)
	log.Println("err:", err, "len_result:", len(result), string(str))
	return result, err
}
